package com.itita.ww2.utils.channel.google;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.itita.ww2.utils.channel.payment.GoogleOrderInfo;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GooglePaymentVerifier {
	private static final Logger logger = LoggerFactory.getLogger(GooglePaymentVerifier.class);
	private Builder builder;

	private GooglePaymentVerifier(Builder builder) {
		this.builder = builder;
	}

	/**
	 * 验证支付(订单验证)
	 */
	public GoogleOrderInfo verify() {
		GoogleOrderInfo ret = null;
		// 验证
		OkHttpClient httpClient = new OkHttpClient.Builder().proxy(this.builder.proxy).build();
		// @formatter:off
		HttpUrl url = HttpUrl.parse(builder.verifyUri);
		Request request = new Request.Builder().url(url).build();
		// @formatter:on
		try {
			Response response = httpClient.newCall(request).execute();
			if (!response.isSuccessful()) {
				logger.warn("error: {}", response.message());
				return ret;
			}
			String body = response.body().string();
			if (StringUtils.isBlank(body)) {
				logger.debug("error: can't get google receipt!");
				return ret;
			}
			JsonObject receiptJson = new JsonParser().parse(body).getAsJsonObject();
			if (receiptJson.has("error")) {
				return ret;
			}
			// logger.info("receiptJson :{}", receiptJson.toString());
			ret = new GoogleOrderInfo(receiptJson.get("developerPayload").getAsString());
			ret.setKind(receiptJson.get("kind").getAsString());
			ret.setPurchaseTime(Long.valueOf(receiptJson.get("purchaseTimeMillis").getAsLong()));
			ret.setPurchaseState(receiptJson.get("purchaseState").getAsInt());
			ret.setConsumptionState(receiptJson.get("consumptionState").getAsInt());
			ret.setProductId(this.builder.productId);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ret;
	}

	public static class Builder {
		private String verifyUri = "https://www.googleapis.com/androidpublisher/v2/applications/{$packageName}/purchases/products/{$productId}/tokens/{$purchaseToken}?access_token={$access_token}";
		private String packageName = "com.itita.ww2aa"; // 游戏包名
		private String productId; // com.itita.cc0001
		private String purchaseToken;
		private String accessToken;
		// 
		private Proxy proxy = Proxy.NO_PROXY;

		public Builder setPackageName(String packageName) {
			if (!this.packageName.equals(packageName)) {
				logger.warn("packageName invalid: [{}] ours: [{}]", packageName, this.packageName);
			}
			this.packageName = packageName;
			return this;
		}

		public Builder setProductId(String productId) {
			this.productId = productId;
			return this;
		}

		public Builder setPurchaseToken(String purchaseToken) {
			this.purchaseToken = purchaseToken;
			return this;
		}

		public Builder setAccessToken(String accessToken) {
			this.accessToken = accessToken;
			return this;
		}

		public Builder setProxy(String type, String host, int port) {
			proxy = new Proxy(Type.valueOf(type.toUpperCase()), new InetSocketAddress(host, port));
			return this;
		}

		public GooglePaymentVerifier build() {
			// @formatter:off
			this.verifyUri = this.verifyUri
					.replace("{$packageName}", this.packageName)
					.replace("{$productId}", this.productId)
					.replace("{$purchaseToken}", this.purchaseToken)
					.replace("{$access_token}", this.accessToken);
			// @formatter:on
			return new GooglePaymentVerifier(this);
		}
	}

	public Builder getBuilder() {
		return builder;
	}
}